/*   
 * Copyright 2010 Rob Schoening
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *    http://www.apache.org/licenses/LICENSE-2.0
 *    
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.beaconframework.vaadin.data;

import java.util.Map;

import javax.xml.transform.Source;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.TransformerFactoryConfigurationError;
import javax.xml.transform.dom.DOMResult;
import javax.xml.transform.dom.DOMSource;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;

import org.beaconframework.util.exception.BeaconException;
import org.beaconframework.util.xml.DomUtil;
import org.beaconframework.util.xml.XPathResolverRegistry;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import com.vaadin.data.Item;

public class XmlItemContainer extends ExpressionItemContainer<Node> {

    public XmlItemContainer() {
        super();
        setExpressionEngineName("xpath");

    }

    private static Logger log = LoggerFactory.getLogger(XmlItemContainer.class);
    static final long serialVersionUID = -4922791081686773486L;

    private String rowXPathExpression;
    private Source transformationSource;
    private XPathResolverRegistry resolverRegistry = new XPathResolverRegistry();


    public XPathResolverRegistry getResolverRegistry() {
        return resolverRegistry;
    }


    public void setResolverRegistry(XPathResolverRegistry resolverRegistry) {
        this.resolverRegistry = resolverRegistry;
    }


    public String getRowXPath() {
        return rowXPathExpression;
    }


    public void setRowXPath(String rowXPathExpression) {
        this.rowXPathExpression = rowXPathExpression;
    }


    public void setTransformationSource(Source s) {
        this.transformationSource = s;
    }


    protected Source getTransformationSource() {
        /*
         * StringReader sr = new StringReader(
         * "<xsl:stylesheet xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\"><xsl:template match=\"@*|node()\"><xsl:copy><xsl:apply-templates select=\"@*|node()\"/></xsl:copy></xsl:template></xsl:stylesheet>"
         * );
         * 
         * StreamSource ss = new StreamSource(sr); return ss;
         */
        return this.transformationSource;
    }


    protected Document doTransform(Document d) {
        Source s = getTransformationSource();

        if (s == null) {
            return d;
        }
        DOMResult dr = new DOMResult(DomUtil.newDocument());
        try {

            TransformerFactory.newInstance().newTransformer(s).transform(
                    new DOMSource(d), dr);
            return (Document) dr.getNode();
        } catch (TransformerConfigurationException e) {
            throw new BeaconException(e);
        } catch (TransformerException e) {
            throw new BeaconException(e);
        } catch (TransformerFactoryConfigurationError e) {
            throw new BeaconException(e);
        }
    }


    public void addDocument(Document d) {
        try {

            Document transformedDocument = doTransform(d);

            XPath xpath = newXPath();
            String rx = getRowXPath();
            getResolverRegistry().attach(xpath);

            if (rx == null) {
                throw new NullPointerException(
                        "XPathExpressionContainer.rowXPath cannot be null");
            }
            XPathExpression x = xpath.compile(getRowXPath());

            addDocument(transformedDocument, x);
        } catch (XPathExpressionException e) {
            throw new BeaconException(e);
        }
    }


    private void addDocument(Document d, XPathExpression x)
            throws XPathExpressionException {
        NodeList nl = (NodeList) x.evaluate(d, XPathConstants.NODESET);
        for (int i = 0; nl != null && i < nl.getLength(); i++) {

            Node n = nl.item(i);
            if (log.isTraceEnabled()) {
                log.trace("adding node #{}: {}", i + 1, n);

                DomUtil.logTrace(log, "node #" + (i + 1), n);
            }
            addItem(n);
        }
    }


    private XPath newXPath() {
        XPath xpath = XPathFactory.newInstance().newXPath();
        getResolverRegistry().attach(xpath);
        return xpath;
    }


    public void addXPathProperty(String propertyName, String xpath) {
        addContainerProperty(propertyName, String.class, "", xpath);
    }


    @Override
    void addContextVariables(Map<String, Object> vars) {
        super.addContextVariables(vars);
        vars.put(XPathResolverRegistry.class.getName(), getResolverRegistry());
    }


    @Override
    protected boolean supports(Class<? extends Object> classToCHeck) {
        return Node.class.isAssignableFrom(classToCHeck);
    }


    @Override
    public Item addItem(Object itemId) throws UnsupportedOperationException {
        if (!supports(itemId.getClass())) {
            throw new IllegalArgumentException(
                    "XmlItemContainer must contain Nodes");
        }
        return super.addItem(itemId);
    }

}
